package com.example.common.codeFactory;

import com.example.common.codeFactory.entity.CodeGenerateType;
import com.example.common.codeFactory.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
// TODO: 用户的编号生成器还没用上
@Component
public final class CodeGenerateStrategyFactory {

    /**
     * 一个生成器仅允许注册一次，不然会出现冲突，建议spring项目使用依赖发现实现此功能
     */
    private final Set<CodeGenerateStrategy> codeGenerateStrategies;


    public CodeGenerateStrategyFactory() {
        codeGenerateStrategies = Set.of(
                new DefaultCodeGenerateStrategy(),
                new DoctorCodeGenrateStrategy(),
                new MenuCodeGenrateStrategy(),
                new RuleCodeGenrateStrategy(),
                new StudentCodeGenerateStrategy(),
                new EntCodeGenrateStrategy(),
                new EssayTypeCodeGenrateStrategy(),
                new ManagerCodeGenerateStrategy()
        );
    }

    public CodeGenerateStrategy getCodeGenerateStrategy(CodeGenerateType codeGenerateType) {
        CodeGenerateStrategy codeGenerateStrategy = null;
        for (CodeGenerateStrategy generateStrategy : codeGenerateStrategies) {
            if (generateStrategy.isSupport(codeGenerateType)) {
                if (codeGenerateStrategy == null) {
                    codeGenerateStrategy = generateStrategy;
                } else {
                    if (codeGenerateStrategy.getPriority() == generateStrategy.getPriority()) {
                        String errorMsg = String.format("【%s】与【%s】规则冲突，请尽快解决",
                                codeGenerateStrategy.getName(), generateStrategy.getName());
                        throw new RuntimeException(errorMsg);
                    } else if (codeGenerateStrategy.getPriority() < generateStrategy.getPriority()) {
                        codeGenerateStrategy = generateStrategy;
                    }
                }
            }
        }
        if (codeGenerateStrategy == null) {
            throw new RuntimeException("未能获取到编码生成规则，请检查编码生成规则是否合适");
        }
        return codeGenerateStrategy;
    }
}
